package com.elitel.frame.base.controller.common;

import com.elitel.frame.base.service.UserInfoService;
import com.elitel.frame.main.entity.ext.ExtUserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Calendar;
import java.util.Map;
import java.util.Optional;

@Controller
public class IndexController {
    @Autowired
    private Environment environment;
    @Autowired
    private UserInfoService userInfoService;

    @Value("${authorize.enable}")
    private boolean securityEnable;

    @RequestMapping("/{module}/index")
    public String toModuleIndex(
            HttpServletRequest request, HttpServletResponse response, @PathVariable String module) {
        Map<String, String[]> map = request.getParameterMap();
        for (String key : map.keySet()) {
            request.setAttribute(key, map.get(key)[0]);
        }

        String uri = IndexUtil.getFuncPage(module);
        if (uri.equals("")) {
            uri = "index";
        }
        return uri;
    }

    @RequestMapping("/index")
    public String indexInGDP(HttpServletRequest request, ModelMap modelMap) {
        return index(request, modelMap);
    }


    @RequestMapping("/")
    public String index(HttpServletRequest request, ModelMap modelMap) {
        if (securityEnable) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Optional<? extends GrantedAuthority> admin =
                    authentication.getAuthorities().stream()
                            .filter(o -> o.getAuthority().equals("ADMIN"))
                            .findFirst();
            modelMap.addAttribute("name", authentication.getName());
            modelMap.addAttribute("isAdmin", admin.isPresent());
            modelMap.addAttribute("securityEnable", securityEnable);
        } else {
            modelMap.addAttribute("name", "管理员");
            modelMap.addAttribute("isAdmin", true);
            modelMap.addAttribute("securityEnable", securityEnable);
        }

        requestSetting(request);
        return "index";
    }


    @GetMapping("/redirectWithRedirectView")
    public RedirectView redirectWithUsingRedirectView(RedirectAttributes attributes) {
        attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectView");
        attributes.addAttribute("attribute", "redirectWithRedirectView");
        return new RedirectView("redirectedUrl");
    }

    @RequestMapping(value = "/redirect", method = RequestMethod.GET)
    public void method(HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Location", "http://localhost:9000/business/singleServer/querySingleTB?serviceID=irr_test_project_code_singleTable_AOMm&pageNO=2&pageSize=20");
        httpServletResponse.setHeader("set-Cookie", "TGC1=111");
        httpServletResponse.setHeader("set-Cookie", "TGC2=222");


        httpServletResponse.addHeader("Set-Cookie","SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
//        httpServletResponse.addHeader("Set-Cookie","luowen=question; Domain=example.com");
        httpServletResponse.addHeader("Set-Cookie","luowen=question; ");


        httpServletResponse.setStatus(302);
    }

    @RequestMapping(value = "/doGet", method = RequestMethod.GET)
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("text/plain");
            resp.addHeader("Set-Cookie","SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");
            resp.addHeader("Set-Cookie","lang=en-US; Path=/; Domain=example.com");
            PrintWriter out = resp.getWriter();
            out.println("Hello From: " + this.getClass().getName());
        }


    private void requestSetting(HttpServletRequest request) {
        try {
            String imageUrl = environment.getProperty("el.logoUrl");
            if (StringUtils.isNotBlank(imageUrl)) {
                String filename = new File(imageUrl).getName();
                String suffix =
                        filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); // 得到点后面的后缀，不包括点
                String imageBase64 = IndexUtil.encodeBase64File(imageUrl);
                if (StringUtils.equals(suffix, "svg")) {
                    suffix = suffix + "+xml";
                }
                request.setAttribute("logoUrl", "data:image/" + suffix + ";base64," + imageBase64);
            } else {
                request.setAttribute("logoUrl", "img/system/Elitel.png");
            }
            String descriptionInfo = environment.getProperty("el.descriptioninfo");
            if (StringUtils.isNotBlank(descriptionInfo)) {
                request.setAttribute("descriptionInfo", descriptionInfo);
            } else {
                Calendar calendar = null;
                calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                request.setAttribute("descriptionInfo", year + " © 北京艾力泰尔信息技术股份有限公司");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/testAjax")
    public String testAjax(HttpServletResponse response) throws IOException {
        return "authorization/ajaxTest";
    }


    @RequestMapping("/updatePassword")
    public String updatePassword() {
        return "authorization/updatePassword";
    }

    @RequestMapping("/userDetail")
    public String userDetail(ModelMap modelMap) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ExtUserInfo extUserInfo = userInfoService.selectByLoginName(authentication.getName());
        if (extUserInfo != null) {
            modelMap.put("user", extUserInfo);
        }
        return "authorization/userDetail";
    }
}
